//
//  HCFileLogger.m
//  HCToolBox
//
//  Created by Hotacool on 2019/3/18.
//

#import "HCFileLogger.h"

@interface HCFileLoggerManager : DDLogFileManagerDefault

@end

@implementation HCFileLoggerManager

- (NSString *)newLogFileName {
    NSDateFormatter *dateFormatter = [self logFileDateFormatter];
    NSString *formattedDate = [dateFormatter stringFromDate:[NSDate date]];
    return [NSString stringWithFormat:@"%@.log", formattedDate];
}

- (NSDateFormatter *)logFileDateFormatter {
    NSMutableDictionary *dictionary = [[NSThread currentThread]
                                       threadDictionary];
    NSString *dateFormat = @"yyyy'-'MM'-'dd'";
    NSString *key = [NSString stringWithFormat:@"logFileDateFormatter.%@", dateFormat];
    NSDateFormatter *dateFormatter = dictionary[key];
    
    if (dateFormatter == nil) {
        dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setLocale:[NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"]];
        [dateFormatter setDateFormat:dateFormat];
        [dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
        dictionary[key] = dateFormatter;
    }
    return dateFormatter;
}

- (BOOL)isLogFile:(NSString *)fileName {
    BOOL hasProperSuffix = [fileName hasSuffix:@".log"];
    return hasProperSuffix;
}
@end

@implementation HCFileLogger

- (instancetype)init {
    HCFileLoggerManager *logManager = [[HCFileLoggerManager alloc] initWithLogsDirectory:[HCFileLogger logsDirectory]];
    HCFileLogger *instance = [self initWithLogFileManager:logManager];
    instance.rollingFrequency = 60 * 60 * 24; // 24 hour rolling
    instance.maximumFileSize = 10 * 1024 * 1024;// 10M
    instance.logFileManager.maximumNumberOfLogFiles = 7;
    return instance;
}

- (void)logMessage:(DDLogMessage *)logMessage {
    //first time to add new log, add marker
    DDLogMessage *__block newMessage = logMessage;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        NSMutableString *mutMessage = [[NSMutableString alloc] initWithString:logMessage.message];
        NSString *str = [NSString stringWithFormat:@"=============Separator: %@=============\n", [NSDate date]];
        [mutMessage insertString:str atIndex:0];
        newMessage = [[DDLogMessage alloc]initWithMessage:mutMessage
                                                    level:logMessage.level
                                                     flag:logMessage.flag
                                                  context:logMessage.context
                                                     file:logMessage.file
                                                 function:logMessage.function
                                                     line:logMessage.line
                                                      tag:logMessage.tag
                                                  options:logMessage.options
                                                timestamp:logMessage.timestamp];
    });
    [super logMessage:newMessage];
}

+ (NSString*)logsDirectory {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *baseDir = paths.firstObject;
    NSString *logsDirectory = [baseDir stringByAppendingPathComponent:[@"Logs-" stringByAppendingString:[[NSBundle mainBundle]bundleIdentifier]]];
    return logsDirectory;
}

+ (NSArray<NSString*>*)logFiles {
    NSMutableArray *fileArr = [NSMutableArray array];
    NSDirectoryEnumerator *enumerator = [[NSFileManager defaultManager] enumeratorAtPath:[HCFileLogger logsDirectory]];
    for (NSString *fileName in enumerator) {
        if ([fileName hasSuffix:@".log"]) {
            [fileArr addObject:fileName];
        }
    }
    return fileArr;
}
@end
